package com.itheima.transaction;

import com.itheima.utils.DatasourceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author huyoufu <https://github.com/huyoufu>
 * @TIME 2020-08-09 11:34
 * @description 事务管理器
 */
@Component
public class TransactionManager {

    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public void begin() throws SQLException {
        Connection connection = dataSource.getConnection();

        //开启事务
        connection.setAutoCommit(false);

        //将连接放到线程去!!!
        DatasourceUtil.setConnection(connection);
    }

    public void commit() throws SQLException {
        Connection connection = DatasourceUtil.getConnection(dataSource);
        if (connection!=null){
            connection.commit();
        }
    }

    public void rollback() {
        Connection connection = DatasourceUtil.getConnection(dataSource);
        if (connection!=null){
            try {
                connection.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
    public void close(){
        Connection connection = DatasourceUtil.getConnection(dataSource);
        if (connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
